<?php

namespace app\job;

use think\Db;
use think\Env;
use think\queue\Job;

class ExportJob
{
    public function fire(Job $job, $data)
    {
        $userId = $data['user_id'];
        $taskId = $data['task_id'];

        $dir = 'export';
        $filePath = 'public' . DIRECTORY_SEPARATOR . $dir . DIRECTORY_SEPARATOR;
        $filename = $taskId . '.csv';

        // 判断目录是否存在
        if (!is_dir($filePath)) {
            mkdir($filePath, 0777, true); // 递归创建目录并设置权限
        }

        // 打开输出流
        $fp = fopen($filePath . $filename, 'w');

        // 设置表头
        $header = ['订单表id', '渠道类型', '渠道id', '店铺id', '订单号', '订单号流水', '订单状态', '订单总金额', '订单总的优惠金额', '履约服务费', '顾客实付金额', '店铺实收金额', '下单时间', '下单日期', '预计送达时间', '自提时间', '是否预约单', '收货人姓名', '收货人电话', '顾客电话', '收货人地址', '地址经度', '地址纬度', '订单类型', '订单备注', '是否拼团订单', '订单是否降级'];
        fputcsv($fp, $header);

        try {
            // 分批查询数据
            $limit = 10000;
            $offset = 0;
            while (true) {
                $data = Db::name('order')->limit($offset, $limit)->select();
                if (empty($data)) {
                    break;
                }
                foreach ($data as $row) {
                    if ($row['type'] == 0) {
                        $row['type'] = '美团';
                    } else if ($row['type'] == 1) {
                        $row['type'] = '饿了么';
                    } else {
                        $row['type'] = '未知';
                    }

                    if ($row['status'] == 1) {
                        $row['status'] = '待支付';
                    } else if ($row['status'] == 2) {
                        $row['status'] = '待接单';
                    } else if ($row['status'] == 4) {
                        $row['status'] = '进行中';
                    } else if ($row['status'] == 8) {
                        $row['status'] = '已完成';
                    } else if ($row['status'] == 9) {
                        $row['status'] = '已取消';
                    } else if ($row['status'] == 10) {
                        $row['status'] = '已退单';
                    } else {
                        $row['status'] = '未知';
                    }

                    if ($row['book'] == 0) {
                        $row['book'] = '默认';
                    } else if ($row['book'] == 1) {
                        $row['book'] = '预定订单';
                    } else if ($row['book'] == 2) {
                        $row['book'] = '即时订单';
                    } else {
                        $row['book'] = '未知';
                    }

                    if ($row['pick_type'] == 0) {
                        $row['pick_type'] = '配送订单';
                    } else if ($row['pick_type'] == 1) {
                        $row['pick_type'] = '到店自取';
                    } else {
                        $row['pick_type'] = '未知';
                    }
                    $row['is_grounp_order'] = $row['is_grounp_order'] == 1 ? '是' : '否';
                    $row['down_graded'] = $row['down_graded'] == 1 ? '是' : '否';
                    $row = [
                        $row['id'],
                        $row['type'],
                        $row['channelshop_id'],
                        $row['shop_id'],
                        $row['order_sn'],
                        $row['order_day_sn'],
                        $row['status'],
                        $row['total_amount'],
                        $row['total_activity_amount'],
                        $row['fulfill_service_fee'],
                        $row['total_price'],
                        $row['income'],
                        $row['createtime'],
                        $row['order_date'],
                        $row['instant_order_deliver_time'],
                        $row['pick_up_time'],
                        $row['book'],
                        $row['recipient_name'],
                        $row['recipient_phone'],
                        $row['user_phone'],
                        $row['recipient_address'],
                        $row['recipient_lng'],
                        $row['recipient_lat'],
                        $row['pick_type'],
                        $row['remark'],
                        $row['is_grounp_order'],
                        $row['down_graded'],
                    ];
                    fputcsv($fp, $row);
                }

                $offset += $limit;
            }
            // 更新任务状态为完成
            Db::name('export_tasks')
                ->where(['task_id' => $taskId])
                ->update([
                    'file_path' => '/' . $dir . '/' . $filename,
                    'status' => 'completed'
                ]);

            fclose($fp);
        } catch (\Exception $e) {
            // 更新任务状态为失败
            Db::name('export_tasks')
                ->where(['task_id' => $taskId])
                ->update(['status' => 'failed']);
        }

        // 标记任务完成（可选）
        $job->delete();
    }
}